from __future__ import annotations

import argparse
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable

from agent_society.ledger.service import Account, LedgerEntry, SessionLocal


@dataclass(slots=True)
class AccountSpec:
    name: str
    balance: int = 0


def load_registry(path: Path) -> list[AccountSpec]:
    data = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(data, dict):
        entries = data.get("accounts", [])
    else:
        entries = data
    specs = []
    for item in entries:
        name = item.get("name")
        if not name:
            raise ValueError("Account entry missing 'name'")
        balance = int(item.get("balance", 0))
        specs.append(AccountSpec(name=name, balance=balance))
    return specs


def seed_accounts(specs: Iterable[AccountSpec]) -> None:
    db = SessionLocal()
    try:
        for spec in specs:
            account = db.query(Account).filter(Account.name == spec.name).first()
            if account:
                continue
            # Create account with zero balance initially
            account = Account(name=spec.name, balance=0)
            db.add(account)
            db.commit()
            db.refresh(account)

            # If initial balance specified, record it as a ledger entry
            if spec.balance > 0:
                account.balance += spec.balance
                entry = LedgerEntry(
                    account=account,
                    delta=spec.balance,
                    reason="initial_balance_bootstrap",
                    correlation_id=None
                )
                db.add(entry)
                db.commit()
                db.refresh(account)
        db.commit()
    finally:
        db.close()


def main() -> None:
    parser = argparse.ArgumentParser(description="Seed ledger accounts from registry JSON")
    parser.add_argument("registry", type=Path, help="Path to account registry JSON")
    args = parser.parse_args()
    specs = load_registry(args.registry)
    seed_accounts(specs)
    print(f"Seeded {len(specs)} account specs")


if __name__ == "__main__":
    main()
